package com.zhongwang.mms.module.material.service;


import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.material.dao.MaterApplyDao;
import com.zhongwang.mms.module.material.model.*;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 库存调整申请 服务层
 * @Author: China.mc
 * @Date: 2020/04/13 16:49
 */
@Service
public class MateApplyService {

    @Autowired
    private MaterApplyDao materApplyDao;
    @Autowired
    private LogService logService;

    /**
     * 调整库存加载列表
     */
    public List<MinventorytModel> selectByPrimaryKey(MinventorytModel minventorytModel) {
        return materApplyDao.findCreateProjectDaily(minventorytModel);
    }

    /**
     * 调整申请加载页面
     */
    public List<MAdjustModel> onefindProjectPage(MAdjustModel madjustModel) {
        return materApplyDao.onefindProjectPage(madjustModel);
    }

    /**
     * 删除未提交数据
     */
    public Integer delProjectStatus(MAdjustModel madjustModel) {
        //通过第一条数据获取同时生成的第二天数据，后台进行统一删除
        MAdjustModel delDateA = materApplyDao.findAdjByOderCode(madjustModel.getAdjId());
        madjustModel.setAdjOrderCode(delDateA.getAdjOrderCode());
        MAdjustModel delDateB = materApplyDao.findAdjByOderCodeTow(madjustModel);
        if (delDateB != null) {
            materApplyDao.updateProjectStatus(delDateB);
        }
        return materApplyDao.updateProjectStatus(delDateA);
    }

    /**
     * 查询库存调整申请表
     */
    public MAdjustModel findviewtDailyId(MAdjustModel madjustModel) {
        return materApplyDao.findviewtDailyId(madjustModel);
    }

    /**
     * 提交待审核数据
     */
    @Transactional
    public Integer updateProjectStatusand(MAdjustModel madjustModel) {
        //通过第一条数据获取同时生成的第二条数据，然后一起提交待审
        MAdjustModel SubmitA = materApplyDao.findAdjByOderCode(madjustModel.getAdjId());
        madjustModel.setAdjOrderCode(SubmitA.getAdjOrderCode());
        MAdjustModel SubmitB = materApplyDao.findAdjByOderCodeTow(madjustModel);
        if (SubmitB != null) {
            materApplyDao.updateProjectStatusand(SubmitB);
        }

        return materApplyDao.updateProjectStatusand(SubmitA);
    }


    /**
     * 根据id查询库存信息
     */
    public MinventorytModel getById(Integer ityId) {
        return materApplyDao.getById(ityId);
    }

    /**
     * 根据id查询物料基础信息
     */
    public List<MmaterialsDic> materialmatId(MmaterialsDic mmaterialsDic) {
        return materApplyDao.materialmatId(mmaterialsDic);
    }

    /**
     * 保存库存物料调整信息
     */
    @Transactional
    public int insterProject(MinventorytModel minventorytModel) {
        User user = ShiroUtils.getUser();
        String adjPerson = user.getName();
        //获取调整后数据
        MAdjustModel mAdjustModel = new MAdjustModel();
        MinventorytModel inventory = materApplyDao.selectByityIdInventory(minventorytModel.getItyId());
        if (!inventory.getItyNum().equals(inventory.getItyAvaNum())) {
            return 0;
        }
        final Integer adjOditStatus = 2;
        final Integer adjStatus = 2;

        String a = minventorytModel.getAdjMatDesc().replace(" ", "");
        String b = inventory.getAdjMatDesc().replace(" ", "");
        if(a.equals(b)){
            a = b;
        }
        //调整时修改物料信息与单价信息时，同时生成入库记录与出库记录
        if ((minventorytModel.getAdjMatDesc() != null && inventory.getAdjMatDesc() != null && !minventorytModel.getAdjMatDesc().replace(" ", "").equals(inventory.getAdjMatDesc().replace(" ", ""))) ||
                (minventorytModel.getAdjMatDesc() == null && inventory.getAdjMatDesc() != null) ||
                (minventorytModel.getAdjMatDesc() != null && inventory.getAdjMatDesc() == null) ||
                (minventorytModel.getItyPrice() != null && inventory.getItyPrice() != null && (!minventorytModel.getItyPrice().equals(inventory.getItyPrice()))) ||
                (minventorytModel.getItyPrice() == null && inventory.getItyPrice() != null) ||
                (minventorytModel.getItyPrice() != null && inventory.getItyPrice() == null)) {
            mAdjustModel.setAdjOditStatus(adjOditStatus);
            mAdjustModel.setAdjStatus(adjStatus);
            mAdjustModel.setAdjDate(new Date());
            mAdjustModel.setAdjPerson(adjPerson);
            mAdjustModel.setAdjAfterMatId(minventorytModel.getMatId());
            mAdjustModel.setAdjMatDesc(minventorytModel.getAdjMatDesc());
            mAdjustModel.setAdjAfterNum(minventorytModel.getItyNum());
            mAdjustModel.setAdjAfterWeight(minventorytModel.getItyWeight());
            mAdjustModel.setAdjTrackCode(minventorytModel.getItyTrackCode());
            mAdjustModel.setAdjInType(minventorytModel.getItyInType());
            mAdjustModel.setAdjSpec(minventorytModel.getItySpec());
            mAdjustModel.setAdjProjectCode(minventorytModel.getItyProCode());
            mAdjustModel.setAdjProjectName(minventorytModel.getItyProName());
            mAdjustModel.setAdjAfterAvaNum(minventorytModel.getItyAvaNum());
            mAdjustModel.setAdjAfterAvaWeight(minventorytModel.getItyAvaWeight());
            mAdjustModel.setAdjPrice(minventorytModel.getItyPrice());//调整后单价
            mAdjustModel.setAdjReason(minventorytModel.getAdjReason());//调整原因
            //获取调整前库存信息
            mAdjustModel.setAdjBeforeAvaNum(inventory.getItyAvaNum());
            mAdjustModel.setAdjBeforeAvaWeight(inventory.getItyAvaWeight());
            mAdjustModel.setAdjBeforeNum(inventory.getItyNum());
            mAdjustModel.setAdjBeforeWeight(inventory.getItyWeight());
            mAdjustModel.setAdjBeforePrice(inventory.getItyPrice());//调整前单价
            mAdjustModel.setAdjInType(inventory.getItyInType());
            mAdjustModel.setAdjOrderCode(createOrderNum());
            mAdjustModel.setAdjBeAfFlag(1);
            mAdjustModel.setAdjNum(minventorytModel.getItyNum());//20200509调整库存量
            mAdjustModel.setAdjWeight(minventorytModel.getItyWeight());//20200512调整库存重量
            mAdjustModel.setAdjType(1);
            mAdjustModel.setMsName(inventory.getItyStoId());
            materApplyDao.oneinsert(mAdjustModel);
            mAdjustModel.setAdjMatDesc(inventory.getAdjMatDesc());
            mAdjustModel.setAdjAfterItyId(inventory.getItyId());
            mAdjustModel.setAdjAfterMatId(inventory.getItyMatId());
            mAdjustModel.setAdjAfterNum(Double.valueOf(0));
            mAdjustModel.setAdjAfterWeight(Double.valueOf(0));
            mAdjustModel.setAdjBeAfFlag(2);
            mAdjustModel.setAdjNum(0 - inventory.getItyNum());
            mAdjustModel.setAdjWeight(0 - inventory.getItyWeight());
            mAdjustModel.setAdjType(1);
            mAdjustModel.setMsName(inventory.getItyStoId());
            materApplyDao.oneinsert(mAdjustModel);
        }
        //没有修改物料信息与单价信息时，只生成一条需要更新的数据
        else {
            mAdjustModel.setAdjMatDesc(minventorytModel.getAdjMatDesc());
            mAdjustModel.setAdjAfterNum(minventorytModel.getItyNum());
            mAdjustModel.setAdjAfterWeight(minventorytModel.getItyWeight());
            mAdjustModel.setAdjTrackCode(minventorytModel.getItyTrackCode());
            mAdjustModel.setAdjInType(minventorytModel.getItyInType());
            mAdjustModel.setAdjSpec(minventorytModel.getItySpec());
            mAdjustModel.setAdjProjectCode(minventorytModel.getItyProCode());
            mAdjustModel.setAdjProjectName(minventorytModel.getItyProName());
            mAdjustModel.setAdjAfterAvaNum(minventorytModel.getItyAvaNum());
            mAdjustModel.setAdjAfterAvaWeight(minventorytModel.getItyAvaWeight());
            mAdjustModel.setAdjPrice(minventorytModel.getItyPrice());//调整后单价
            mAdjustModel.setAdjReason(minventorytModel.getAdjReason());
            mAdjustModel.setAdjDate(new Date());
            mAdjustModel.setAdjPerson(adjPerson);
            mAdjustModel.setAdjStatus(adjStatus);
            // 获取调整前数据
            mAdjustModel.setAdjBeforeAvaNum(inventory.getItyAvaNum());
            mAdjustModel.setAdjBeforeAvaWeight(inventory.getItyAvaWeight());
            mAdjustModel.setAdjBeforeNum(inventory.getItyNum());
            mAdjustModel.setAdjBeforeWeight(inventory.getItyWeight());
            mAdjustModel.setAdjBeforePrice(inventory.getItyPrice());//调整前单价
            mAdjustModel.setAdjInType(inventory.getItyInType());
            mAdjustModel.setAdjAfterMatId(inventory.getItyMatId());
            mAdjustModel.setAdjAfterItyId(inventory.getItyId());
            mAdjustModel.setAdjNum(minventorytModel.getItyNum() - inventory.getItyNum());
            //重量损益差转值
            Double difValue = minventorytModel.getItyWeight() - inventory.getItyWeight();
            DecimalFormat df = new DecimalFormat("0.00");
            mAdjustModel.setAdjWeight(Double.parseDouble(df.format(difValue)));
            mAdjustModel.setAdjType(1);
            // 调整库存时修改库存信息状态
            materApplyDao.insert(mAdjustModel);
        }
        return 1;
    }

    /**
     * 修改物料信息与单价信息时，同时生成相同编码规则
     *
     * @return
     */
    private String createOrderNum() {
        // 取得当日零时时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        // 查询当日是否有调整单记录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String date1 = dateFormat.format(date);
        Date date2 = null;
        try {
            date2 = dateFormat.parse(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<MAdjustModel> mInveAdjModel = materApplyDao.findAdjByDate(date2);
        String adjOrderCode; // 调整单编号生成规则：MADJ200317001

        if (mInveAdjModel.size() == 0) //如果当日没有调整单，则生成第一条
        {
            adjOrderCode = "MADJ" + dateFormat.format(new Date()).substring(2, 8) + "001";
        } else //如果已有调整单，则查找最后一个调整单号，按顺序生成下一个调整单号
        {
            adjOrderCode = "MADJ" + dateFormat.format(new Date()).substring(2, 8) + String.format("%03d", Integer.parseInt(mInveAdjModel.get(mInveAdjModel.size() - 1).getAdjOrderCode().substring(10, 13)) + 1);
        }
        return adjOrderCode;
    }


    /**
     * 库存申请时修改库存信息回显
     */
    public MAdjustModel getByUpdateAdjId(Integer adjId) {

        return materApplyDao.getByUpdateAdjId(adjId);
    }

    /**
     * 修改库存调整
     */
    public int getByUpdateAdjIdAdd(MAdjustModel mAdjustModel) {
        int row = materApplyDao.getByUpdateAdjIdAdd(mAdjustModel);
        return row;
    }

    /**
     * 库存调整时新增库存信息
     */
    public int insertStock(MAdjustModel madjustModel) {
        User user = ShiroUtils.getUser();
        String adjPerson = user.getName();
        final Integer adjStatus = 2;
        final Integer adjOditStatus = 1;
        madjustModel.setAdjStatus(adjStatus);
        madjustModel.setAdjOditStatus(adjOditStatus);
        madjustModel.setAdjPerson(adjPerson);
        madjustModel.setAdjDate(new Date());
        madjustModel.setAdjAfterMatId(madjustModel.getMatId());
        madjustModel.setAdjOrderCode(createOrderNum());
        madjustModel.setAdjNum(madjustModel.getAdjAfterNum());
        madjustModel.setAdjWeight(madjustModel.getAdjAfterWeight());
        madjustModel.setAdjType(1);
        madjustModel.setAdjProjectCode(madjustModel.getAdjProjectCode().toUpperCase()); // 小写转大写
        return materApplyDao.insertStock(madjustModel);
    }

    /**
     * 库存调整申请批量提交
     *
     * @param arr 标记Id集合
     * @return
     */
    @Transactional
    public void updateProjectStatustogetherAnd(List<Integer> arr) {

        for (int i = 0; i < arr.size(); i++) {
            //通过第一条数据获取同时生成的第二条数据，然后一起提交待审
            MAdjustModel SubmitA = materApplyDao.findAdjByOderCode(arr.get(i));
            MAdjustModel SubmitB = materApplyDao.findAdjByOderCodeTow(SubmitA);
            if (SubmitB != null) {
                materApplyDao.updateProjectStatusand(SubmitB);
            }

            materApplyDao.updateProjectStatusand(SubmitA);
        }

        logService.saveLog("库存调整申请批量提交", "批量提交" + arr.size() + "条");
    }

}





